package com.fintech.third.service.sign.wukong;

import java.time.LocalDateTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dragon.common.util.PropertiesLoadUtil;
import com.fintech.common.util.RedisUtils;
import com.fintech.third.service.exception.DefineException;
import com.fintech.user.entity.RealNameAuthentication;
import com.fintech.user.service.RealNameAuthenticationService;
import com.marvels.approve.process.dao.McamSignOrgInfoMapper;
import com.marvels.approve.process.dto.McamSignOrgInfo;
import com.marvels.common.utils.MarvelsLogUtil;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;

/**
 * @author helichao
 * @Description
 * @Date 2021/01/29 20:38:44
 */
@Service
public class WuKongSignService {

	@Value("${wukong.copier_acct_id}")
	private String copierAcctId;

	@Value("${wukong.notice.developer.url}")
	private String wukongNoticeDeveloperUrl;

	@Autowired
	private  RealNameAuthenticationService realNameAuthenticationService;
	@Autowired
	private McamSignOrgInfoMapper mcamSignOrgInfoMapper;

	private final static String PRESON_AUTO_SIGN_KEY_PRE = "PRESON_AUTO_SIGN_";

	/**
	 * @param idNo
	 * @param mobileNo
	 * @return
	 */
	public String createPersonAcct(String name,String idNo,String mobileNo) {
		String acctId = null;
		try {
				JSONObject personAcctJson = AccountHelper.createPersonAcct(idNo,name,null,idNo,mobileNo,null);
				MarvelsLogUtil.getInstance().info("WuKongSignService.createPersonAcct result==>"+personAcctJson.toJSONString()
				);
				if(null == personAcctJson) {
					return acctId;
				}
				MarvelsLogUtil.getInstance().info("WuKongSignService.createPersonAcct result==>"+personAcctJson.toJSONString());
				acctId = personAcctJson.getString("accountId");
				if(StringUtils.isBlank(acctId)) {
					return acctId;
				}
		} catch (DefineException e) {
			MarvelsLogUtil.getInstance().error("WuKongSignService.createPersonAcct error" ,e);
			return acctId;
		}
		return acctId;
	}

	public String createOrgAcct(McamSignOrgInfo mcamSignOrgInfo,String empAcctId) {
		String orgId = null;
		try {
				JSONObject orgAccountJson = AccountHelper.createOrgAcct(mcamSignOrgInfo.getOrgCode(), empAcctId, mcamSignOrgInfo.getOrgName(), "CRED_ORG_USCC", mcamSignOrgInfo.getOrgCode());
				if(null == orgAccountJson) {
					return orgId;
				}
				MarvelsLogUtil.getInstance().info("e签宝创建机构签署账号 result==>"+orgAccountJson.toJSONString());
				orgId = orgAccountJson.getString("orgId");
				if(StringUtils.isBlank(orgId)) {
					return orgId;
				}
		} catch (DefineException e) {
			MarvelsLogUtil.getInstance().error("WuKongSignService.createPersonAcct error" ,e);
			return orgId;
		}
		return orgId;
	}

	public String oneStepFlow(String filePath,String fileName,String idNo,String mobileNo) {
		String flowId = null;
		try {
			String acctId = null;
			RealNameAuthentication accountInfo = realNameAuthenticationService.querByIdentiyCardNo(idNo);
			MarvelsLogUtil.getInstance().info("WuKongSignService.createPersonAcct start,param==>"+JSON.toJSONString(accountInfo)+",mobileNo="+mobileNo);
			TokenHelper.getTokenData();
			acctId = accountInfo.getSignAccoutId();
			if(StringUtils.isBlank(acctId)) {
				acctId = createPersonAcct(accountInfo.getRealName(),idNo,mobileNo);
				if(StringUtils.isBlank(acctId)) {
					return flowId;
				}
				RealNameAuthentication modifyAccountInfo = new RealNameAuthentication();
				modifyAccountInfo.setSignAccoutId(acctId);
				modifyAccountInfo.setId(accountInfo.getId());
				realNameAuthenticationService.update(modifyAccountInfo);
			}

			String autoSignKey = PRESON_AUTO_SIGN_KEY_PRE+acctId;
			String autoSign = RedisUtils.getInstance().get(autoSignKey);
//			if(StringUtils.isEmpty(autoSign)) {
//				AccountHelper.setAutoSign(acctId, DateUtil.format(LocalDateTime.now().plusDays(1), DatePattern.NORM_DATETIME_PATTERN));
//				RedisUtils.getInstance().setex(autoSignKey, 72000, acctId);
//			}

			String signOrgCode = PropertiesLoadUtil.getPropertiesValue("sign.org.code", "resource.properties");
			MarvelsLogUtil.getInstance().info("e签宝签约配置的签署机构代码："+signOrgCode);
			McamSignOrgInfo mcamSignOrgInfo = mcamSignOrgInfoMapper.getOne(signOrgCode);
			if(null == mcamSignOrgInfo) {
				MarvelsLogUtil.getInstance().info("e签宝签约配置的签署机构代码："+signOrgCode+",在数据库中未配置");
				return flowId;
			}
			String orgId = mcamSignOrgInfo.getOrgSignAcctId();
			if(StringUtils.isEmpty(orgId)) {

				String empAcctId = mcamSignOrgInfo.getEmpSignAcctId();
				if(StringUtils.isEmpty(empAcctId)) {
					//创建机构签署方账号
					empAcctId = createPersonAcct(mcamSignOrgInfo.getEmpName(),mcamSignOrgInfo.getEmpCardNo(),mcamSignOrgInfo.getEmpMobileNo());
					if(StringUtils.isEmpty(empAcctId)) {
						return flowId;
					}
					mcamSignOrgInfo.setEmpSignAcctId(empAcctId);
				}

				orgId = createOrgAcct(mcamSignOrgInfo,empAcctId);
				mcamSignOrgInfo.setOrgSignAcctId(orgId);
				mcamSignOrgInfoMapper.update(mcamSignOrgInfo);
				if(StringUtils.isEmpty(orgId)) {
					return flowId;
				}
				//机构账号自动签署授权
//				AccountHelper.setAutoSign(orgId, null);
			}

			MarvelsLogUtil.getInstance().info("WuKongSignService.oneStepFlow start [wukongNoticeDeveloperUrl="+wukongNoticeDeveloperUrl+"] [copierAcctId="+copierAcctId+"][filePath="+filePath+"][fileName="+fileName+"][acctId="+acctId+"]");
			JSONObject uploadJson = FileTemplateHelper.createFileByUpload(filePath, fileName, acctId);
			if(null == uploadJson) {
				return flowId;
			}
			MarvelsLogUtil.getInstance().info("WuKongSignService.oneStepFlow1 call result==>"+uploadJson.toJSONString());
			String uploadUrl = uploadJson.getString("uploadUrl");
			String fileId = uploadJson.getString("fileId");

			JSONObject fileUploadResult = FileTemplateHelper.streamUpload(filePath, uploadUrl);
			MarvelsLogUtil.getInstance().info("文件上传结果==>"+JSON.toJSONString(fileUploadResult));

			JSONObject flowJson = SignHelper.oneStepFlow(wukongNoticeDeveloperUrl,copierAcctId, fileId, fileName,orgId, acctId);
			if(null == flowJson) {
				return flowId;
			}
			MarvelsLogUtil.getInstance().info("WuKongSignService.oneStepFlow2 call result==>"+flowJson.toJSONString());
			flowId = flowJson.getString("flowId");

//			SignHelper.startSignFlow(flowId);
		} catch (DefineException e) {
			MarvelsLogUtil.getInstance().error("WuKongSignService.createPersonAcct error" ,e);
			return null;
		}
		return flowId;

	}

	public String downloadFlowDoc(String flowId) throws Exception{
		    String fileUrl = null;
		    //MarvelsLogUtil.getInstance().info("开始下载已签署合同，flowId：" + flowId);
			TokenHelper.getTokenData();
			JSONObject jsonObject = SignHelper.downloadFlowDoc(flowId);
			//MarvelsLogUtil.getInstance().info("开始下载已签署合同，flowId：" + flowId+"，返回结果："+jsonObject.toJSONString());
			String docs = jsonObject.getString("docs");
			if(StringUtils.isNotBlank(docs)) {
				JSONArray docsJsonArray = JSONArray.parseArray(docs);
				JSONObject json = (JSONObject)docsJsonArray.get(0);
				fileUrl = json.getString("fileUrl");
			}
			return fileUrl;
	}
	public static void main(String[] args) {
		WuKongSignService service = new WuKongSignService();
		try {
			service.downloadFlowDoc("36db7c8c22504fcb9fe48af0883228bc");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
